<template>
  <div class="storage-repair">
    <h2>存储空间修复工具</h2>
    <p class="description">
      如果您发现存储空间统计不正确（删除文件后存储空间没有减少），可以使用此工具修复。
    </p>

    <!-- 检查结果 -->
    <el-card v-if="checkResult" class="check-result">
      <template #header>
        <span>存储空间检查结果</span>
      </template>
      <div class="result-content">
        <div class="result-item">
          <span class="label">当前记录的存储使用量:</span>
          <span class="value">{{ formatFileSize(checkResult.currentStorageUsed) }}</span>
        </div>
        <div class="result-item">
          <span class="label">实际存储使用量:</span>
          <span class="value">{{ formatFileSize(checkResult.actualStorageUsed) }}</span>
        </div>
        <div class="result-item">
          <span class="label">差异:</span>
          <span class="value" :class="{ 'error': !checkResult.isConsistent }">
            {{ checkResult.differenceFormatted }}
          </span>
        </div>
        <div class="result-item">
          <span class="label">状态:</span>
          <el-tag :type="checkResult.isConsistent ? 'success' : 'warning'">
            {{ checkResult.isConsistent ? '正常' : '需要修复' }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 修复结果 -->
    <el-card v-if="repairResult" class="repair-result">
      <template #header>
        <span>存储空间修复结果</span>
      </template>
      <div class="result-content">
        <div class="result-item">
          <span class="label">修复前:</span>
          <span class="value">{{ formatFileSize(repairResult.beforeRepair) }}</span>
        </div>
        <div class="result-item">
          <span class="label">修复后:</span>
          <span class="value">{{ formatFileSize(repairResult.afterRepair) }}</span>
        </div>
        <div class="result-item">
          <span class="label">修复差异:</span>
          <span class="value">{{ repairResult.differenceFormatted }}</span>
        </div>
        <div class="result-item">
          <span class="label">修复状态:</span>
          <el-tag type="success">
            {{ repairResult.isFixed ? '已修复' : '无需修复' }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="actions">
      <el-button 
        type="primary" 
        @click="checkStorage"
        :loading="checking"
      >
        检查存储空间
      </el-button>
      
      <el-button 
        type="warning" 
        @click="repairStorage"
        :loading="repairing"
        :disabled="!checkResult || checkResult.isConsistent"
      >
        修复存储空间
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../../api/request'

// 状态
const checking = ref(false)
const repairing = ref(false)
const checkResult = ref<any>(null)
const repairResult = ref<any>(null)

// 检查存储空间
const checkStorage = async () => {
  checking.value = true
  checkResult.value = null
  repairResult.value = null
  
  try {
    const response = await request.get('/storage/repair/check-current-user')
    // console.log('检查响应:', response.data) // 开发调试用

    // 获取检查结果数据（API直接返回数据，不需要.data.data）
    checkResult.value = response.data

    if (checkResult.value && checkResult.value.isConsistent) {
      ElMessage.success('存储空间统计正常')
    } else if (checkResult.value) {
      ElMessage.warning('存储空间统计不一致，建议修复')
    } else {
      ElMessage.error('检查结果数据格式错误')
    }
  } catch (error: any) {
    ElMessage.error('检查失败: ' + (error.response?.data?.message || error.message))
  } finally {
    checking.value = false
  }
}

// 修复存储空间
const repairStorage = async () => {
  repairing.value = true
  repairResult.value = null
  
  try {
    const response = await request.post('/storage/repair/current-user')
    // console.log('修复响应:', response.data) // 开发调试用

    // 获取修复结果数据（API直接返回数据，不需要.data.data）
    repairResult.value = response.data

    if (repairResult.value && repairResult.value.isFixed) {
      ElMessage.success('存储空间修复完成')
      // 重新检查
      setTimeout(() => {
        checkStorage()
      }, 1000)
    } else if (repairResult.value) {
      ElMessage.info('存储空间无需修复')
    } else {
      ElMessage.error('修复结果数据格式错误')
    }
  } catch (error: any) {
    ElMessage.error('修复失败: ' + (error.response?.data?.message || error.message))
  } finally {
    repairing.value = false
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>

<style lang="scss" scoped>
.storage-repair {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.description {
  margin-bottom: 20px;
  color: #666;
  line-height: 1.6;
}

.check-result,
.repair-result {
  margin-bottom: 20px;
}

.result-content {
  .result-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    .label {
      font-weight: 500;
      color: #333;
    }
    
    .value {
      font-family: monospace;
      
      &.error {
        color: #f56c6c;
        font-weight: bold;
      }
    }
  }
}

.actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}
</style>
